package org.cuit.lmq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.cuit.lmq.constants.enums.RedisKeyEnum;
import org.cuit.lmq.domain.common.BaseContextHolder;
import org.cuit.lmq.domain.po.User;
import org.cuit.lmq.domain.security.LoginUser;
import org.cuit.lmq.mapper.UserMapper;
import org.cuit.lmq.service.UserService;
import org.cuit.lmq.utils.JwtUtil;
import org.cuit.lmq.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Seon
 * @since 2023-03-03
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 1. 进行对应的认证，没过的话给出对应的提示
     * 2. 认证通过了，就用userid生成一个token
     * 3. 把完整的信息存入redis，userid作为key，用户信息作为value
     */
    @Override
    public String login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (ObjectUtils.isNull(authenticate)) {
            throw new RuntimeException("认证失败");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        User onlineUser = loginUser.getUser();
        String token = JwtUtil.createJWT(onlineUser.getId().toString(), onlineUser.getPassword(), JwtUtil.JWT_TTL);
        String redisKey = RedisKeyEnum.LOGIN_USER.getValue() + onlineUser.getId();
        redisCache.setCacheObject(redisKey, loginUser);
        return token;
    }

    @Override
    public boolean signup(User user) {
        try {
            String password = user.getPassword();
            password = passwordEncoder.encode(password);
            user.setPassword(password);
            user.setStatus("0");
            user.setSex(2);
            this.save(user);
        } catch (RuntimeException re) {
            re.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean logout() {
        Long id = BaseContextHolder.getCurrentUserId();
        String redisKey = RedisKeyEnum.LOGIN_USER.getValue() + id;
        if (redisCache.deleteObject(redisKey)) {
            log.info("id = {}, 用户已经下线了", id);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public User getUserByName(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = this.getOne(wrapper);
        return user;
    }

    @Override
    public boolean modifyPassword(String oldPwd, String newPwd) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String oldPwdSecret = loginUser.getPassword();
        boolean matches = passwordEncoder.matches(oldPwd, oldPwdSecret);
        try {
            if (matches) {
                String newPwdSecret = passwordEncoder.encode(newPwd);
                User user = loginUser.getUser();
                user.setPassword(newPwdSecret);
                this.updateById(user);
                return true;
            } else {
                return false;
            }
        } catch (RuntimeException re) {
            re.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean forgotPassword(String email, String newPwd) {
        try {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getEmail, email);
            User user = this.getOne(wrapper);
            if (ObjectUtils.isNull(user)) {
                return false;
            }
            String newPwdSecret = passwordEncoder.encode(newPwd);
            user.setPassword(newPwdSecret);
            this.updateById(user);
        } catch (RuntimeException re) {
            re.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean modifyEmail(String email) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User user = loginUser.getUser();
        user.setEmail(email);
        boolean result = this.updateById(user);
        return result;
    }
}
